declare var signals: signals.SignalWrapper;


declare namespace signals {
    interface SignalWrapper<T = any> {
        Signal: Signal<T>;
    }

    interface SignalBinding<T = any> {
        active: boolean;
        context: any;
        params: any;
        detach(): Function;
        execute(paramsArr?: any[]): any;
        getListener(): (...params: T[]) => void;
        getSignal(): Signal<T>;
        isBound(): boolean;
        isOnce(): boolean;
    }
    
}

class SignalBinding<T = any>{
    _listener:(...params: T[]) => void;
    private _isOnce;
    private _signal;
    context;
    _priority;
    active=true;
    params:any[]|null=null;
    constructor(signal:Signal, listener:(...params: T[]) => void, isOnce?:boolean, listenerContext?:any, priority?:number) {

        this._listener = listener;

        this._isOnce = isOnce;

        this.context = listenerContext;


        this._signal = signal;

    
        this._priority = priority || 0;
    }

    /**
     * Call listener passing arbitrary parameters.
     * <p>If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.</p>
     * @param {Array} [paramsArr] Array of parameters that should be passed to the listener
     * @return {*} Value returned by the listener.
     */
    execute(paramsArr:any[]) :any {
        var handlerReturn, params;
        if (this.active && !!this._listener) {
            params = this.params? this.params.concat(paramsArr) : paramsArr;
            handlerReturn = this._listener.apply(this.context, params);
            if (this._isOnce) {
                this.detach();
            }
        }
        return handlerReturn;
    }

    /**
     * Detach binding from signal.
     * - alias to: mySignal.remove(myBinding.getListener());
     * @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached.
     */
    detach() {
        return this.isBound()? this._signal.remove(this._listener, this.context) : null;
    }

    /**
     * @return {Boolean} `true` if binding is still bound to the signal and have a listener.
     */
    isBound() {
        return (!!this._signal && !!this._listener);
    }

    /**
     * @return {boolean} If SignalBinding will only be executed once.
     */
    isOnce() {
        return this._isOnce;
    }

    /**
     * @return {Function} Handler function bound to the signal.
     */
    getListener() {
        return this._listener;
    }

    /**
     * @return {Signal} Signal that listener is currently bound to.
     */
    getSignal() {
        return this._signal;
    }

    /**
     * Delete instance properties
     * @private
     */
    _destroy() {
        // delete this._signal;
        // delete this._listener;
        delete this.context;
    }

    /**
     * @return {string} String representation of the object.
     */
    toString() {
        return '[SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
    }

};

function validateListener<T>(listener: (...params: T[]) => void, fnName:string) {
    if (typeof listener !== 'function') {
        throw new Error( 'listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName) );
    }
}

export class Signal<T = any> {
    private _bindings?:SignalBinding<T>[]=[];
    private _prevParams?:T[]|null = null;
    private _shouldPropagate = true;

    VERSION = '1.0.0';
    memorize = false;
    active = true;

    constructor(){
        
    }
    static dispatch(){
        const args=arguments as any;
        Signal.prototype.dispatch.apply(self, args);
    }

    /**
     * @param {Function} listener
     * @param {boolean} isOnce
     * @param {Object} [listenerContext]
     * @param {Number} [priority]
     * @return {SignalBinding}
     * @private
     */
    private _registerListener(listener: (...params: T[]) => void, isOnce:boolean, listenerContext?: any, priority?:number) {

        var prevIndex = this._indexOfListener(listener, listenerContext),
            binding;

        if (prevIndex!=undefined&&prevIndex !== -1&&this._bindings) {
            binding = this._bindings[prevIndex];
            if (binding.isOnce() !== isOnce) {
                throw new Error('You cannot add'+ (isOnce? '' : 'Once') +'() then add'+ (!isOnce? '' : 'Once') +'() the same listener without removing the relationship first.');
            }
        } else {
            binding = new SignalBinding(this, listener, isOnce, listenerContext, priority);
            this._addBinding(binding);
        }

        if(this.memorize && this._prevParams){
            binding.execute(this._prevParams);
        }

        return binding;
    }

    /**
     * @param {SignalBinding} binding
     * @private
     */
    _addBinding(binding:SignalBinding) {
        //simplified insertion sort
        if(this._bindings){
            var n = this._bindings.length;
            do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
        this._bindings.splice(n + 1, 0, binding);
        }
    }

    /**
     * @param {Function} listener
     * @return {number}
     * @private
     */
    _indexOfListener(listener: (...params: T[]) => void, context?: any) {
        if(!this._bindings)return;
        var n = this._bindings.length,
            cur;
        while (n--) {
            cur = this._bindings[n];
            if (cur._listener === listener && cur.context === context) {
                return n;
            }
        }
        return -1;
    }

    /**
     * Check if listener was attached to Signal.
     * @param {Function} listener
     * @param {Object} [context]
     * @return {boolean} if Signal has the specified listener.
     */
    has(listener: (...params: T[]) => void, context?: any): boolean{
        return this._indexOfListener(listener, context) !== -1;
    }

    /**
     * Add a listener to the signal.
     * @param {Function} listener Signal handler function.
     * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
     * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
     * @return {SignalBinding} An Object representing the binding between the Signal and listener.
     */
    add(listener: (...params: T[]) => void, listenerContext?: any, priority?:number) {
        validateListener(listener, 'add');
        return this._registerListener(listener, false, listenerContext, priority);
    }

    /**
     * Add listener to the signal that should be removed after first execution (will be executed only once).
     * @param {Function} listener Signal handler function.
     * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
     * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
     * @return {SignalBinding} An Object representing the binding between the Signal and listener.
     */
    addOnce(listener: (...params: T[]) => void, listenerContext?: any, priority?:number) {
        validateListener(listener, 'addOnce');
        return this._registerListener(listener, true, listenerContext, priority);
    }

    /**
     * Remove a single listener from the dispatch queue.
     * @param {Function} listener Handler function that should be removed.
     * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
     * @return {Function} Listener handler function.
     */
    remove(listener: (...params: T[]) => void, context?: any) {
        validateListener(listener, 'remove');

        var i = this._indexOfListener(listener, context);
        if (i!==undefined&&i !== -1&&this._bindings) {
            this._bindings[i]._destroy(); //no reason to a SignalBinding exist if it isn't attached to a signal
            this._bindings.splice(i, 1);
        }
        return listener;
    }

    /**
     * Remove all listeners from the Signal.
     */
    removeAll() {
        if(!this._bindings)return;
        var n = this._bindings.length;
        while (n--) {
            this._bindings[n]._destroy();
        }
        this._bindings.length = 0;
    }

    /**
     * @return {number} Number of listeners attached to the Signal.
     */
    getNumListeners() {
        return this._bindings?.length||0;
    }

    /**
     * Stop propagation of the event, blocking the dispatch to next listeners on the queue.
     * <p><strong>IMPORTANT:</strong> should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.</p>
     * @see Signal.prototype.disable
     */
    halt() {
        this._shouldPropagate = false;
    }

    /**
     * Dispatch/Broadcast Signal to all listeners added to the queue.
     * @param {...*} [params] Parameters that should be passed to each handler.
     */
    dispatch(...params: T[]) {
        if (! this.active) {
            return;
        }
        if(!this._bindings)return;

        var paramsArr = Array.prototype.slice.call(arguments),
            n = this._bindings.length,
            bindings;

        if (this.memorize) {
            this._prevParams = paramsArr;
        }

        if (! n) {
            //should come after memorize
            return;
        }

        bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
        this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.

        //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
        //reverse loop since listeners with higher priority will be added at the end of the list
        do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
    }

    /**
     * Forget memorized arguments.
     * @see Signal.memorize
     */
    forget(){
        this._prevParams = null;
    }

    /**
     * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
     * <p><strong>IMPORTANT:</strong> calling any method on the signal instance after calling dispose will throw errors.</p>
     */
    dispose() {
        this.removeAll();
        delete this._bindings;
        delete this._prevParams;
    }

    /**
     * @return {string} String representation of the object.
     */
    toString() {
        return '[Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
    }

};

